package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.po.Entity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

@Controller
@RequestMapping("httpClientController")
public class HttpClientController {

    /*
     * 带参数的get请求调用天气预报接口
     * */

    @RequestMapping("getWeather")
    @ResponseBody
    public Entity getWeather() throws Exception {
        //1.创建一个HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建URIBuilder http://wthrcdn.etouch.cn/weather_mini?city=沈阳
        URIBuilder uriBuilder = new URIBuilder("http://wthrcdn.etouch.cn/weather_mini");
        //设置参数
        /*
         * 第一个参数是参数名称
         * 第二个参数是参数的值
         * */
        uriBuilder.setParameter("city","北京");
        //2.创建一个Get请求,设置url访问地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        CloseableHttpResponse response = null;
        String content = null;
        Entity entity = new Entity();
        try {
            //3.使用HttpClient来执行Get请求,获取response
            response = httpClient.execute(httpGet);
            //4.处理response,解析相应  200:响应成功
            if(response.getStatusLine().getStatusCode() == 200){
                /*
                 * 第一个参数是响应体
                 * 第二个参数是编码格式
                 * */
                content = EntityUtils.toString(response.getEntity(), "utf8");
//                System.out.println("响应状态为:"+response.getStatusLine());
//                System.out.println("响应内容为:"+ content);
                entity = JSONObject.parseObject(content, Entity.class);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //5.释放资源
                if(response != null){
                    response.close();
                }if(httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return entity;
    }
}
